﻿using AutoMapper;
using ManagementApi.Models;
using ManagementApi.Models.Account;
using ManagementApi.Models.Corp;
using ManagementApi.Models.System.AuditLog;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Authorization;
using ManagementApi.TreeParty.SMS;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Corp;
using Modules.SMS;
using Modules.System.Security;
using Modules.System.User;
using PmSoft.Entity;
using PmSoft.Exceptions;
using PmSoft.Utilities;
using System.ComponentModel.DataAnnotations;
using static Modules.Audit.SysAuditLogConstants;

namespace ManagementApi.Controllers.AdminPannel
{
    /// <summary>
    /// 企业管理
    /// </summary>
    [Route("/api/v1/sysuser/Corp")]
    [ApiController]
    [Authorize(Roles = "SysUser")]
    public class CorpController : ControllerBase
    {
        private readonly CorpService corpService;
        private readonly ManagementApplicationContext applicationContext;
        private readonly IMapper mapper;
        private readonly SecurityService securityService;
        private readonly ISMSService sMSService;
        private readonly IConfiguration configuration;

        public CorpController(CorpService corpService, ManagementApplicationContext applicationContext, IMapper mapper, SecurityService securityService, ISMSService sMSService, IConfiguration configuration)
        {
            this.corpService = corpService;
            this.applicationContext = applicationContext;
            this.mapper = mapper;
            this.securityService = securityService;
            this.sMSService = sMSService;
            this.configuration = configuration;
        }

        /// <summary>
        /// 企业分页
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<PageDto<CorpInfoDto>> GetCorpInfos([FromQuery] CorpInfoQuery query, int pageNum = 1, int pageSize = 20)
        {
            var corps = corpService.GetCorpInfos(query, pageNum, pageSize);
            var dtos = corps.AsPageDto(source => { return source.AsDto(applicationContext); });
            return ApiResult<PageDto<CorpInfoDto>>.Success(dtos);
        }

        /// <summary>
        /// 企业详情
        /// </summary>
        /// <param name="corpId"></param>
        /// <returns></returns>
        [HttpGet("{corpId}/form")]
        public ApiResult<CorpDetailDto> GetCorpInfo(int corpId)
        {
            var data = corpService.GetCorpInfo(corpId);
            if (data == null)
                return ApiResult<CorpDetailDto>.Failure("企业数据不存在");
            //CorpInfoDto corpCreateForm = new();
            //mapper.Map(data, corpCreateForm);
            return ApiResult<CorpDetailDto>.Success(data.AsDetailDto(applicationContext));
        }

        /// <summary>
        /// 修改企业信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="from"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        [PermissionCheck("corp:corpinfo:edit")]
        public ApiResult Update(int id, CorpCreateForm from)
        {
            CorpInfo? data = corpService.GetCorpInfo(id);
            if (data == null)
                return ApiResult.Failure("企业数据不存在");
            mapper.Map(from, data);
            corpService.UpdateCorpInfo(data, from.Attachments);
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// 删除企业信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [PermissionCheck("corp:corpinfo:delete")]
        public ApiResult Deleted(string ids)
        {
            corpService.Deletes(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("resetPassword/{id}")]
        [PermissionCheck("corp:corpinfo:resetpassword")]
        public ApiResult EditPassWord(int id, [Required(ErrorMessage = "密码不能为空")] string passWord)
        {
            CorpInfo? data = corpService.GetCorpInfo(id);
            if (data == null)
                return ApiResult.Failure("企业数据不存在");
            SysSecurity? sysSecurity = securityService.GetSysSecurity(data.SecurityId);
            if (sysSecurity != null)
            {
                sysSecurity.Password = SecurityPasswordHelper.EncodePassword(passWord, UserPasswordFormat.SM4);
                securityService.Update(sysSecurity);
            }
            else
            {
                sysSecurity = new()
                {
                    Password = SecurityPasswordHelper.EncodePassword(passWord, UserPasswordFormat.SM4),
                    UserType = UserType.Corp,
                    IsAuth = false
                };
                securityService.Create(sysSecurity);
            }
            return ApiResult.Success("密码重置成功");
        }

        /// <summary>
        /// 审核企业
        /// </summary>
        /// <param name="id"></param>
        /// <param name="auditForm"></param>
        /// <returns></returns>
        [HttpPut("{id}/audit")]
        [PermissionCheck("corp:corpinfo:audit")]
        public ApiResult AuditCorpInfo(int id, AuditForm auditForm)
        {
            SmsModel smsModel;
            var corp = corpService.GetCorpInfo(id) ?? throw new BusinessException("企业信息不存在");
            var mobile = corp.LinkTel;
            if (auditForm.AuditIdea == AuditIdea.同意)
            {
                corpService.AuditCorpSuccess(id);
                smsModel = SmsBuidler.Instance().CorpVerifySuccess(corp.Name, corp.Code);
                if (string.IsNullOrEmpty(mobile)) return ApiResult.Success("审核成功");
                applicationContext.GetService<SmsSendLogService>().Send(mobile, smsModel);
                return ApiResult.Success("审核成功,已发送短信提示");
            }
            if (auditForm.AuditIdea == AuditIdea.不同意)
            {
                corpService.AuditCorpFail(id, auditForm.AuditIdeaContent ?? string.Empty);
                smsModel = SmsBuidler.Instance().CorpVerifyFail(corp.Name, corp.Code);
                if (string.IsNullOrEmpty(mobile)) return ApiResult.Success("审核成功");
                applicationContext.GetService<SmsSendLogService>().Send(mobile, smsModel);
                return ApiResult.Success("审核成功,已发送短信提示");
            }

            return ApiResult.Failure("审核失败，错误的审核类型");
        }
    }
}